<?php
/**
 * excel操作功能
 */

namespace app\common\component;

class Excel
{
    /**
     * 生成excel
     * @param $filename
     * @param $data
     */
    public function formatExcel($filename, $data)
    {
        $filename = $filename . '_' . date('YmdHis') . mt_rand(1, 10) . '.csv';
        $filepath = RUNTIME_PATH . 'excel/' . $filename;
        if (!is_dir(dirname($filepath))) {
            mkdir(dirname($filepath), 0777);
        }

        $fp = fopen($filepath, 'w');
        if (!$fp) {
            return false;
        }
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
        foreach ($data as $row) {
            fputcsv($fp, $row);
        }
        fclose($fp);
        return $filename;
    }

    /**
     * 下载文件
     * @param $filename
     * @throws \Exception
     */
    public function downloadExcel($filename)
    {
        $filepath = RUNTIME_PATH . 'excel/' . $filename;
        if (is_file($filepath)) {
            $fp = fopen($filepath, 'r');
            if (!$fp) {
                throw new \Exception('文件打开失败');
            }
            $filesize = filesize($filepath);
            header("Content-type: application/vnd.ms-excel;charset=UTF-8");
            header("Content-type: text/csv");
            header('Accept-Ranges:bytes');
            header('Accept-Length:'.$filesize);
            header("Content-Disposition: attachment; filename={$filename}");
            header("Pragma: no-cache");
            header("Expires: 0");
            $read_buffer = 4096;
            $sum_buffer = 0;
            //只要没到文件尾，就一直读取
            while(!feof($fp) && $sum_buffer < $filesize) {
                echo fread($fp, $read_buffer);
                $sum_buffer += $read_buffer;
            }
            fclose($fp);
            // 下载后就转移文件
            $newFilepath = RUNTIME_PATH . 'excel/already_' . $filename;
            copy($filepath, $newFilepath);
            unlink($filepath);
        } else {
            throw new \Exception('文件不存在');
        }
    }
}